<?php

class Quad_Data_Address extends Quad_Data_Abstract {
	
	public $raw;
	public $propertyList;
	public static $defaultPropertyList = array(
		'address1','address2','city','province','postal_code'
	);
	
	public function __construct($raw, $propertyList = null) {
		$this->raw = $raw;
		$object = $raw;
		if (is_array($object)) {
			$o = new stdClass;
			foreach ($object as $k => $v) {
				$o->$k = $v;
			}
			$object = $o;
		}
		$this->object = $object;
		$this->propertyList = (is_array($propertyList) ? $propertyList : self::$defaultPropertyList);
	}
	
	public static function create($object, $propertyList = null) {
		return new self($object, $propertyList);
	}
	
	public function isValid() {
		$address1 = (string) $this->object->{$this->propertyList[0]};
		$city = (string) $this->object->{$this->propertyList[2]};
		$province = (string) $this->object->{$this->propertyList[3]};
		$postal_code = (string) $this->object->{$this->propertyList[4]};
		return ($address1 !== '' && $city !== '' && $province !== '' && $postal_code !== '');		
	}
	
	public function format($linefeed = "\n") {
		$out = '';
		$address1 = (string) $this->object->{$this->propertyList[0]};
		$address2 = (string) $this->object->{$this->propertyList[1]};
		$city = (string) $this->object->{$this->propertyList[2]};
		$province = (string) $this->object->{$this->propertyList[3]};
		$postal_code = (string) $this->object->{$this->propertyList[4]};
		
		$out .= ($address1 ? $address1 . $linefeed : ''); 
		$out .= ($address2 ? $address2 . $linefeed : ''); 
		$out .= ($city ? $city . ' ' : ''); 
		$out .= ($province ? $province . ($postal_code ? ', ' : '') : ''); 
		$out .= ($postal_code ? $postal_code : '');
		 
		return $out;
	}
	
}